<template>
  <el-dialog
    :title="!dataForm.id ? '新增任务' : '修改任务'"
    :close-on-click-modal="false" style="min-width: 1400px;"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="120px" label-position="right">
      <el-form-item label="任务名称：" prop="name">
        <el-input v-model="dataForm.name" placeholder="任务名称" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item label="生效时间：" prop="strategy">
        <el-select v-model="dataForm.strategy" multiple placeholder="请选择" style="width: 500px;">
          <el-option
            v-for="item in strategyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <div v-for="(taskItem,index) in taskItemList" :key="index">
        <div style="display: flex;">
          <div class="label-wrap">
            <span class="task-delete" @click="deleteTaskItem(index)">x</span>
            <span class="label">{{'子任务'+(index+1)+'：'}}</span></div>
          <div
            style="margin-bottom: 8px;">
            <div style="display: flex;flex-direction: row;justify-content: left;">
              <el-select v-model="taskItem.pbTaskItem.type" placeholder="请选择">
                <el-option
                  v-for="item in petTaskTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <input placeholder="时长/数量" class="num-input price-input" @input="onInput" ref="total" type="number"/>
              <el-autocomplete
                style="width: 240px;margin: 0 10px;"
                v-model="taskItem.pbTaskItem.nameCode"
                clearable
                :hide-loading="true"
                :fetch-suggestions="querySearch"
                placeholder="请输入绘本ID或者绘本名称"
                :trigger-on-focus="false"
                @select="handlePicBookSelect"
                @focus="getPicBookFocusInput(taskItem.pbTaskItem,index)">
                <template slot-scope="{ item }">
                  <div>{{ item.nameCode }}</div>
                </template>
              </el-autocomplete>
              <el-select v-model="taskItem.pbTaskItem.bookItemId"
                         v-if="taskItem.itemList&&taskItem.itemList.length>0">
                <el-option
                  v-for="subItem in taskItem.itemList"
                  :key="subItem.id"
                  :label="subItem.itemName"
                  :value="subItem.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <el-form-item label="奖励：">
          <div style="display: flex;flex-direction: row;justify-content: left;flex-wrap: wrap;">
            <div v-for="(reward,rewardIndex) in taskItem.rewards"
                 style="display: flex;flex-direction: row;margin-right: 10px;margin-bottom: 10px;align-items: center;"
                 :key="rewardIndex">
              <span class="task-delete" @click="deleteRewardItem(index,rewardIndex)">x</span>
              <el-select v-model="reward.rewardName" style="width: 110px;">
                <el-option
                  v-for="(rewardOption,optionIndex) in petRewardOptions"
                  :key="optionIndex"
                  :label="rewardOption.name"
                  :value="rewardOption.name">
                </el-option>
              </el-select>
              <input placeholder="数量" class="num-input" :ref="'count'+index" @input="onInput"
                     type="number"/>
            </div>
          </div>
          <el-button type="primary" size="mini" @click="addRewardItem(index)" v-if="taskItem.rewards.length<5">添加
          </el-button>
        </el-form-item>
      </div>
      <el-form-item v-if="taskItemList.length<5">
        <el-button type="primary" @click="addTaskItem" size="small">新增子任务</el-button>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <div style="margin-left: 80px;color:#f56c6c;" v-if="showErrorTip">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>还有信息未填完整，请检查！
    </div>
    <div style="margin-left: 80px;">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>{{attentionTip}}
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        showErrorTip: false,
        attentionTip: '暂时最多只能添加5个子任务，每个子任务最多添加5个奖励',
        selectedInputItemIndex: 0,
        petTaskTypeOptions: [],
        petRewardOptions: [],
        strategyOptions: [{value: '2', label: '周一'}, {value: '3', label: '周二'}, {value: '4', label: '周三'},
          {value: '5', label: '周四'}, {value: '6', label: '周五'}, {value: '7', label: '周六'}, {value: '1', label: '周日'}],
        dataForm: {
          'name': '',
          'strategy': [],
        },
        pbTaskGroup: {
          'createTime': '',
          'cron': '',
          'id': '',
          'name': '',
          'remark': '',
          'status': '',
          'strategy': '',
          'updateTime': ''
        },
        taskItemList: [{
          itemList: [],
          pbTaskItem: {
            'bookId': '',
            'bookItemId': '',
            'createTime': '',
            'id': '',
            'itemName': '',
            'orders': '',
            'remark': '',
            'taskGroupId': '',
            'total': '',
            'type': '',
            'updateTime': '',
            'nameCode': '',
          },
          rewards: [{
            'count': '',
            'createTime': '',
            'id': '',
            'img': '',
            'petPropId': '',
            'remark': '',
            'rewardName': '',
            'rewardType': '',
            'taskItemId': '',
            'updateTime': '',
            'selectedIndex': ''
          }]
        }],
        dataRule: {
          name: [
            {required: true, message: '任务名称不能为空', trigger: 'blur'}
          ],
          strategy: [
            {required: true, message: '生效时间不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      onInput (e) {
        // 通过正则过滤小数点后两位
        e.target.value = (e.target.value.match(/^\d*/g)[0]) || null
      },
      init (id) {
        let _this = this
        _this.visible = true
        _this.$nextTick(() => {
          _this.resetData()
          _this.dataForm.id = id || ''
          _this.getPetTaskTypeList()
          _this.getRewardList()
        })
      },
      resetData () {
        let _this = this
        _this.selectedInputItemIndex = 0
        _this.dataForm = {
          'name': '',
          'strategy': [],
        },
          _this.pbTaskGroup = {
            'createTime': '',
            'cron': '',
            'id': '',
            'name': '',
            'remark': '',
            'status': '',
            'strategy': '',
            'updateTime': ''
          }
        _this.taskItemList = []
        _this.taskItemList.push(_this.getCopyTaskItem())
        _this.taskItemList.map(function (taskItem, taskItemIndex) {
          taskItem.rewards.map(function (reward, rewardIndex) {
            _this.$refs['count' + taskItemIndex][rewardIndex].value = ''
          })
          _this.$refs['total'][taskItemIndex].value = ''
        })
      },
      initData () {
        let _this = this
        if (_this.dataForm.id) {
          _this.$http({
            url: _this.$http.adornUrl(`/picbook/pbtaskgroup/info/${_this.dataForm.id}`),
            method: 'get',
            params: _this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              _this.pbTaskGroup = data.data.pbTaskGroup
              _this.taskItemList = data.data.items
              _this.dataForm.strategy = data.data.pbTaskGroup.strategy.split(',')
              _this.dataForm.name = data.data.pbTaskGroup.name
              setTimeout(() => {
                _this.taskItemList.map(function (taskItem, taskItemIndex) {
                  _this.$refs['total'][taskItemIndex].value = taskItem.pbTaskItem.total
                  taskItem.rewards.map(function (reward, rewardIndex) {
                    _this.$refs['count' + taskItemIndex][rewardIndex].value = reward.count
                  })
                })
              }, 50)
            }
          })
        }
      },
      //获取宠物任务类型下拉框
      getPetTaskTypeList () {
        this.$http({
          url: this.$http.adornUrl(`/picbook/combobox/listPetTaskType`),
          method: 'post',
          data: this.$http.adornData()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.petTaskTypeOptions = data.data
          }
        })
      },
      //获取宠物任务奖励下拉框
      getRewardList () {
        let _this = this
        this.$http({
          url: this.$http.adornUrl(`/picbook/combobox/listSimpleReward`),
          method: 'post',
          data: this.$http.adornData()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.petRewardOptions = data.data
            //获取详情
            _this.initData()
          }
        })
      },
      getPicBookFocusInput (item, index) {
        this.selectedInputItemIndex = index
      },
      querySearch (queryString, cb) {
        this.$http({
          url: this.$http.adornUrl('/picbook/combobox/listSimpleBook'),
          method: 'post',
          data: this.$http.adornData({
            'text': queryString
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            cb(data.data)
          } else {
            cb([])
          }
        }).catch(() => {
          cb([])
        })
      },
      handlePicBookSelect (item) {
        let _this = this
        _this.taskItemList[_this.selectedInputItemIndex].pbTaskItem.bookId = item.id
        _this.taskItemList[_this.selectedInputItemIndex].pbTaskItem.nameCode = item.nameCode
        //查询绘本子项
        _this.$http({
          url: _this.$http.adornUrl(`/picbook/combobox/listSimpleItem/` + item.id),
          method: 'post',
          data: _this.$http.adornData({
            'bookId': item.id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            _this.taskItemList[_this.selectedInputItemIndex].pbTaskItem.bookItemId = ''
            _this.taskItemList[_this.selectedInputItemIndex].itemList = data.data
          }
        })
      },
      addTaskItem () {
        let maxCount = 5
        if (this.taskItemList.length < maxCount) {
          this.taskItemList.push(this.getCopyTaskItem())
        } else {
          this.$message.warning('最多只能添加' + maxCount + '个子任务')
        }
      },
      addRewardItem (index) {
        let maxCount = 5
        if (this.taskItemList[index].rewards.length < maxCount) {
          this.taskItemList[index].rewards.push(this.getCopyRewardItem())
        } else {
          this.$message.warning('最多只能添加' + maxCount + '个奖励')
        }
      },
      deleteTaskItem (index) {
        let _this = this
        if (_this.taskItemList.length > index && _this.taskItemList.length > 1) {
          _this.taskItemList.splice(index, 1)
        } else if (index == 0 && this.taskItemList.length == 1) {
          _this.taskItemList.splice(0, 1)
          _this.taskItemList.push(_this.getCopyTaskItem())
          _this.taskItemList.map(function (taskItem, taskItemIndex) {
            taskItem.rewards.map(function (reward, rewardIndex) {
              _this.$refs['count' + taskItemIndex][rewardIndex].value = ''
            })
            _this.$refs['total'][taskItemIndex].value = ''
          })
        }
      },
      deleteRewardItem (taskItemIndex, rewardIndex) {
        let _this = this
        if (_this.taskItemList.length > taskItemIndex && _this.taskItemList[taskItemIndex].rewards.length > rewardIndex) {
          var rewards = _this.taskItemList[taskItemIndex].rewards
          let rewardsSize = rewards.length
          if (rewardsSize > 1) {
            rewards.splice(rewardIndex, 1)
          } else if (rewardIndex == 0 && rewardsSize == 1) {
            rewards.splice(0, 1)
            rewards.push(_this.getCopyRewardItem())
            _this.$refs['count' + taskItemIndex][rewardIndex].value = ''
          }
        }
      },
      // 表单提交
      dataFormSubmit () {
        let _this = this
        _this.showErrorTip = false
        _this.taskItemList.map(function (taskItem, taskItemIndex) {
          if (!taskItem.pbTaskItem.type) {
            _this.showErrorTip = true
            return
          } else {
            if (_this.$refs['total'][taskItemIndex].value === '' && (!taskItem.pbTaskItem.bookId || !taskItem.pbTaskItem.bookItemId)) {
              _this.showErrorTip = true
              return
            }
            if ((taskItem.pbTaskItem.bookId && !taskItem.pbTaskItem.bookItemId) || (!taskItem.pbTaskItem.bookId && taskItem.pbTaskItem.bookItemId)) {
              _this.showErrorTip = true
              return
            }
          }
          taskItem.rewards.map(function (reward, rewardIndex) {
            if (reward.rewardName === '') {
              _this.showErrorTip = true
              return
            } else {
              if (_this.$refs['count' + taskItemIndex][rewardIndex].value === '') {
                _this.showErrorTip = true
                return
              }
            }
            reward.count = _this.$refs['count' + taskItemIndex][rewardIndex].value
            _this.petRewardOptions.map(function (option) {
              if (reward.rewardName === option.name) {
                reward.rewardType = option.type
                reward.petPropId = option.id
              }
            })
          })
          taskItem.pbTaskItem.total = _this.$refs['total'][taskItemIndex].value
        })
        _this.$refs['dataForm'].validate((valid) => {
          if (valid && !_this.showErrorTip) {
            _this.pbTaskGroup.strategy = _this.dataForm.strategy.join(',')
            _this.pbTaskGroup.name = _this.dataForm.name
            _this.$http({
              url: _this.$http.adornUrl(`/picbook/pbtaskgroup/${!_this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: _this.$http.adornData({
                items: _this.taskItemList,
                pbTaskGroup: _this.pbTaskGroup
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                _this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    _this.visible = false
                    _this.$emit('refreshDataList')
                  }
                })
              } else {
                _this.$message.error(data.msg)
              }
            })
          }
        })
      },
      getCopyTaskItem () {
        return Object.assign({}, {
          itemList: [],
          pbTaskItem: {
            'bookId': '',
            'bookItemId': '',
            'createTime': '',
            'id': '',
            'itemName': '',
            'orders': '',
            'remark': '',
            'taskGroupId': '',
            'total': '',
            'type': '',
            'updateTime': '',
            'nameCode': '',
          },
          rewards: [{
            'count': '',
            'createTime': '',
            'id': '',
            'img': '',
            'petPropId': '',
            'remark': '',
            'rewardName': '',
            'rewardType': '',
            'taskItemId': '',
            'updateTime': '',
            'selectedIndex': ''
          }]
        })
      },
      getCopyRewardItem () {
        return Object.assign({}, {
          'count': '',
          'createTime': '',
          'id': '',
          'img': '',
          'petPropId': '',
          'remark': '',
          'rewardName': '',
          'rewardType': '',
          'taskItemId': '',
          'updateTime': '',
          'selectedIndex': ''
        })
      }
    }
  }
</script>
<style scoped lang="less">
  .num-input {
    width: 80px;
    margin-left: 10px;
    height: 36px;
    line-height: 36px;
    border-radius: 4px;
    -webkit-appearance: none;
    border: 1px solid #dcdfe6;
    color: #606266;
    padding: 0 15px;
  }

  .price-input {
    width: 120px;
  }

  /** 去除input输入框样式 */
  input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }

  input::-webkit-input-placeholder {
    /* placeholder颜色  */
    color: #c0c4cc;
  }

  .label-wrap {
    width: 120px;
    display: flex;
    justify-content: flex-end;
    padding-right: 12px;
    height: 36px;
    align-items: center;
    .label {
      font-size: 14px;
      color: #606266;
    }
  }

  .task-delete {
    border-radius: 8px;
    width: 16px;
    height: 16px;
    background-color: #bbbbbb;
    line-height: 16px;
    text-align: center;
    color: white;
    font-size: 10px;
    margin-right: 5px;
    cursor: pointer;
  }
</style>
